package com.systop.party05.http;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.systop.party05.utils.LoggerUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.util.Map;

import okhttp3.MediaType;

import static com.systop.party05.utils.StaticDateUtils.PAGE;


/**
 * @author gengqiufang
 * @describtion 公共网络请求
 * @created at 2019/1/9
 */
public class CommonOkhttp {

    public CommonOkhttp() {
    }

    public void execute(String url, Map<String, String> map, MyStringCallback callback) {
        PostFormBuilder builder = OkHttpUtils.post();
        LoggerUtil.i("==网址", url);
        builder.url(url);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (TextUtils.isEmpty(entry.getKey())) {
                LoggerUtil.i("存在入参名为空");
            } else if (TextUtils.isEmpty(entry.getValue())) {
                LoggerUtil.i("存在入参值为空");
                builder.addParams(entry.getKey(), "");
            } else {
                builder.addParams(entry.getKey(), entry.getValue());
            }
        }
        LoggerUtil.i("==入参", new Gson().toJson(map));
        builder.build().execute(callback);
    }

    public void execute8(String url, Map<String, String> map, MyStringCallback callback) {
        String str="";
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (TextUtils.isEmpty(entry.getKey())) {
                LoggerUtil.i("存在入参名为空");
            } else if (TextUtils.isEmpty(entry.getValue())) {
                LoggerUtil.i("存在入参值为空");
                str+=entry.getKey()+"="+""+"&";
            } else {
                str+=entry.getKey()+"="+entry.getValue()+"&";
            }
        }
        if (!TextUtils.isEmpty(str)){
            str= str.substring(0,str.length()-1);
        }
        LoggerUtil.i("==网址", url);
        LoggerUtil.i("==入参", str.replace("&","\n"));
        OkHttpUtils
                .postString()
                .url(url)
                .mediaType(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8")) //设置post的字符串为json字符串并设置编码
                .content(str) //用Gson将User对象转化为Json字符串的形式作为content
                .build().execute(callback);
    }

    public void refreshComplete(int page, SmartRefreshLayout refreshLayout) {
        if (refreshLayout == null) return;
        if (page == PAGE) {
            refreshLayout.finishRefresh(0/*,false*/);//传入false表示刷新失败
        } else {
            refreshLayout.finishLoadMore(0/*,false*/);//传入false表示加载失败
        }
    }

    public void refreshCompleteF(int page, SmartRefreshLayout refreshLayout) {
        if (refreshLayout == null) return;
        if (page == PAGE) {
            refreshLayout.finishRefresh(false);//传入false表示刷新失败
        } else {
            refreshLayout.finishLoadMore(false);//传入false表示加载失败
        }
    }
}
